package cn.zhouchao.org.service.impl;

import cn.zhouchao.basic.service.impl.BaseServiceImpl;
import cn.zhouchao.org.domain.Department;
import cn.zhouchao.org.domain.Employee;
import cn.zhouchao.org.mapper.DepartmentMapper;
import cn.zhouchao.org.service.IDepartmentService;
import cn.zhouchao.system.ann.Anndept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> deptTree() {
        //创建一个新的空的部门数组集合
        ArrayList<Department> list = new ArrayList<>();//通过后面的判断后，分出父子级，再返回给前端
        //通过查询所有部门对象
        List<Department> all = departmentMapper.findAll();
        //通过stream流将所有的部门对象装入map集合,并以部门对象的id为key,部门对象为value值
        Map<Long, Department> map = all.stream().collect(Collectors.toMap(Department::getId, dept -> dept));
        //遍历查询的所有部门对象
        for (Department dept : all) {
            if (null==dept.getParentId()){
                //没有就以顶级父类加入集合
                list.add(dept);
            }else {
                //有子级部门的对象，找到他的父级
                Department department = map.get(dept.getParentId());//通过父级key找到父级value
                //父级再打开父级对象获取子级的get方法
                List<Department> children = department.getChildren();//通过父对象，找到子对象
                //将子级装进父级的Children里面，便于我们通过部门树从父级当中去取
                if(null != department){//避免父部门为空
                    children.add(dept);
                }
            }
        }
        //返回装入集合的那些部门对象
        return list;
    }

    @Override
    public List<Employee> findEmpByDeptId(Long id) {
        return departmentMapper.findEmpByDeptId(id);
    }

    @Anndept(des = "新增部门方法", methodname = "add")
    @Override
    public void add(Department department) {
        super.add(department);
    }

    @Anndept(des = "删除部门方法", methodname = "delete")
    @Override
    public void delete(Long id) {
        super.delete(id);
    }

    @Anndept(des = "批量删除部门方法", methodname = "batchDelete")
    @Override
    public void batchDelete(List<Long> ids) {
        super.batchDelete(ids);
    }

    @Anndept(des = "修改部门方法", methodname = "update")
    @Override
    public void update(Department department) {
        super.update(department);
    }
}
